package com.heima.wemedia.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.AuditService;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WmNewsMapper vmNewMapper;

    @Autowired
    private AuditService auditService;
    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.非空判断
        dto.checkParam();
        //2.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
        //2.1 根据状态查询
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //2.2 根据关键字查询
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //2.3 根据频道id查询
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //2.4 根据开始和结束时间查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }

        //2.5 根据登录用户id查询
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = super.page(page, queryWrapper);

        //3.返回数据结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 保存-修改-提交草稿为一体的方法
     * 主方法
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        //TODO
        WmUser user = WmThreadLocalUtil.getUser();
        WmNews wmNews = new WmNews();
        wmNews.setTitle(dto.getTitle());
        wmNews.setContent(dto.getContent());
       // wmNews.setType(dto.getType());
        wmNews.setChannelId(dto.getChannelId());
        wmNews.setCreatedTime(DateTime.now());
        wmNews.setPublishTime(dto.getPublishTime());
        wmNews.setLabels(dto.getLabels());
        wmNews.setStatus(dto.getStatus());
        wmNews.setUserId(user.getId());
        if (dto.getImages().size() == 0) {
            wmNews.setImages(null);
        } else {
            String img = "";
            if (dto.getImages() != null && !dto.getImages().isEmpty()) {
                img = String.join(",", dto.getImages());
            }
            wmNews.setImages(img);}
        //1.判断id是否为空
        if (!Objects.isNull(dto.getId())) {
            LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(WmNewsMaterial::getNewsId, dto.getId());
            //3.不为空的话为修改文章
            //3.1删除文章素材关系表中new_id对应的数据
            wmNewsMaterialMapper.delete(wrapper);
        }
        //2.1为空的话为新增文章
        //4.判断是否为草稿
        if (dto.getStatus()==0) {
            //是草稿的话直接存储
            wmNews.setType(dto.getType());
            vmNewMapper.insert(wmNews);
            return ResponseResult.okResult("成功存储草稿箱");
            }
        List<Integer> materialId=new ArrayList<>();
        for (String image : dto.getImages()) {
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setType((short) 0);
            wmMaterial.setUrl(image);
            wmMaterial.setCreatedTime(DateTime.now());
            wmMaterial.setUserId(user.getId());
            wmMaterialMapper.insert(wmMaterial);
            Integer id = wmMaterial.getId();
            materialId.add(id);
        }
        //5.不是的话判断封面选择是否为自动
        if (dto.getType() == -1) {
            //5.1写匹配规则
            List<String> images = dto.getImages();
            //无图：设置封面为无图结构
            if (images.size()==0){
                wmNews.setImages(null);
                wmNews.setType((short) 0);
            }else if (images.size()>=1&&images.size()<3){
                //图片大于等于1，小于3，选一张作为封面，封面布局为单图
                wmNews.setImages(images.get(0));
                wmNews.setType((short) 1);
            }else {
                //图片数量大于三，选三张作为封面，设置布局为多图布局
                wmNews.setImages(images.get(0)+","+images.get(1)+","+images.get(2));
                wmNews.setType((short) 3);
            }
        }else {
            wmNews.setType(dto.getType());
        }
        vmNewMapper.insert(wmNews);
        Integer newsId = wmNews.getId();//获取自媒体id
        //将关系表插入数据
        for (Integer mId : materialId) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setMaterialId(mId);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }

        //调用异步线程的方法
        auditService.AuditImageAndText(wmNews);

        //6.返回数据
        return ResponseResult.okResult("发布文章完成");
    }


    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //TODO
        return ResponseResult.okResult("文章上下架完成");
    }
}
